//
//  WEXHomeTableViewController.swift
//  microBlog
//
//  Created by apple on 16/4/16.
//  Copyright © 2016年 Hill. All rights reserved.
//

import UIKit

let WEXStatusIdentifier: String = "weiboCell"

class WEXHomeTableViewController: WEXBaseTableViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        if !userLogon {
            
            visitor.setVisitorInfo(nil, message: nil )
            return
        }
        
        //初始化界面
        setupUI()
        
        //加载数据
        loadData()
        
    }
    
    // MARK: - 初始化UI界面
    private func setupUI() {
        
//        设置tableView的背景颜色
        tableView.backgroundColor = UIColor(white: 180 / 255.0 , alpha: 1)
        
        self.tableView.registerClass(WEXWeiboCell.self, forCellReuseIdentifier: WEXStatusIdentifier)
        
//        自动计算行高
        tableView.rowHeight = UITableViewAutomaticDimension
        
//        预估一个cell的高度
        tableView.estimatedRowHeight = 250
        
//        隐藏分割线
        tableView.separatorStyle = .None
        
//        设置组尾为菊花
        tableView.tableFooterView = pullView
        
//        添加自定义下拉刷新控件
        tableView.addSubview(refreshContrl)
        
        refreshContrl.addTarget(self, action: "loadData", forControlEvents: UIControlEvents.ValueChanged)
        
        self.navigationController?.view.addSubview(pullDownTips)
        
        self.navigationController!.view.insertSubview(pullDownTips, belowSubview: self.navigationController!.navigationBar)
        
        
    }
    
    // MARK: - 获取数据
   @objc private func loadData() {
        

            statusListViewModel.loadData(pullView.isAnimating() , finished: { (isSuccess, count) -> () in
                
                if isSuccess {
                    
                    self.tableView.reloadData()
                    
                }else{
                    
                    print("输出错误")
                }
                
                if self.pullView.isAnimating() == false {
                    
                    self.showPullDownTips(count)
                    
                }
                
                //            完成回调，停止动画
                self.endAnim()
            })
        }
    
    // 显示刷新label
    private func showPullDownTips(count: Int){
        
        if pullDownTips.hidden == false {
            
            return
        }
        
        pullDownTips.frame.origin.y = CGRectGetMaxY(self.navigationController!.navigationBar.frame) - pullDownTips.frame.size.height
        
        self.pullDownTips.hidden = false
        
        let text = count > 0 ? "\(count)条新微博" : "没有新的微博"
        
        pullDownTips.text = text
        
        UIView.animateWithDuration(1, animations: { () -> Void in
            
            self.pullDownTips.transform = CGAffineTransformMakeTranslation(0, self.pullDownTips.frame.size.height)
            
            }) { (_) -> Void in
                
                UIView.animateWithDuration(1, delay: 0.5, options: [], animations: { () -> Void in
                    
                    self.pullDownTips.transform = CGAffineTransformIdentity
                    
                    }, completion: { (_) -> Void in
                        
                        self.pullDownTips.hidden = true
                        
                })
        }
        
        
        
    }
    
    // MARK: - 停止动画方法
    private func endAnim() {
        
        pullView.stopAnimating()
        refreshContrl.endRefreshing()
    }
    
    // MARK: - 懒加载子控件
    
//    底部刷新
    private lazy var pullView: UIActivityIndicatorView = {
        
        let pullView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
        
        pullView.color = UIColor.greenColor()
        
        return pullView
    }()
    
    private lazy var statusListViewModel: WEXStatusListViewModel = WEXStatusListViewModel()
    
//    自定义下拉刷新
    private lazy var refreshContrl: WEXRefreshControl = WEXRefreshControl()
    
//    下拉刷新提示
    private lazy var pullDownTips: UILabel = {
        
        
        let label = UILabel(textColor: UIColor.darkGrayColor(), textFont: 14)
        
        label.backgroundColor = UIColor.orangeColor()
        label.frame.size = CGSize(width: SCREENWIDTH, height: 35)
        label.textAlignment = .Center
        label.hidden = true
        
        return label
        
    
    }()
    
}


// MARK: - tableView数据源方法实现
extension WEXHomeTableViewController {
    
    
    
    override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        
        if indexPath.row == statusListViewModel.statusArray!.count - 1 && !pullView.isAnimating() {
            
            
            pullView.startAnimating()
            
            loadData()
            
        }
        
        
    }
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return self.statusListViewModel.statusArray?.count ?? 0
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCellWithIdentifier(WEXStatusIdentifier, forIndexPath: indexPath) as! WEXWeiboCell
        
        //        cell.textLabel?.text = statusListViewModel.statusArray![indexPath.row].text
        
        cell.statusViewMdoel = statusListViewModel.statusArray![indexPath.row]
        
        return cell
    }
    
    
    
    
    
}